<template>
  <div>
    <LabelValue label="过敏史" :label-class="labelClass" :value-class="valueClass" :width="width" :value="gmsValue" tooltip @click="openModal" />
    <SelectAllergyModal v-model:open="allergyModal" v-model:value="formState.brGms" :source-data="formState.patientAllergys" @success="onSuccess" />
  </div>
</template>
<script setup>
import { message } from 'ant-design-vue'
import { getAgeUnit } from '@/utils/format'
import SelectAllergyModal from './SelectAllergyModal.vue'

const props = defineProps({
  width: {
    type: Number,
    default: 200
  },
  value: {
    type: String,
    default: ''
  },
  patientInfo: {
    type: Object,
    default: () => ({})
  },
  labelClass: {
    type: String,
    default: 'underline cursor-pointer text-primary'
  },
  valueClass: {
    type: String,
    default: 'underline cursor-pointer text-primary text-red-600'
  }
})

// const emit = defineEmits(['success'])
const gmsValue = ref('')
const allergyModal = ref(false)
const formState = ref({})

const openModal = async () => {
  if (!props.patientInfo.brId) return message.warning('请先选择患者')
  const { code, data, msg } = await get('/common/patient/getPatientInfo?br_id=' + props.patientInfo.brId)
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  formState.value = data || {}
  allergyModal.value = true
}
const onSuccess = async (val) => {
  formState.value = {
    ...formState.value,
    brGms: val.value,
    patientAllergys: val.data
  }
  const res = await post('/common/patient/savePatientInfo', {
    ...formState.value,
    brAge: getAgeUnit(formState.value.brAge).brAge
  })
  if (res.code !== 0) return message.error(res.msg || '保存患者信息失败')
  message.success(res.msg || '保存成功')
  const { code, data, msg } = await get('/common/patient/getPatientInfo?br_id=' + props.patientInfo.brId)
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  // emit('success', data.brGms)
  gmsValue.value = formatValue(data.patientAllergys, data.brGms)
  allergyModal.value = false
}

const formatValue = (patientAllergys, gms) => {
  let result = ''
  if (patientAllergys && patientAllergys.length > 0) {
    const selectArr = patientAllergys.filter((item) => {
      return item.status === 2
    })
    if (selectArr && selectArr.length > 0) {
      selectArr.forEach((item, index) => {
        if (selectArr.length === index + 1) {
          result += item.dictItemName + ' (+)'
        } else {
          result += item.dictItemName + ' (+)' + '、'
        }
      })
      gms && (result = result + '、' + gms)
    } else {
      gms && (result = gms)
    }
  } else {
    gms && (result = gms)
  }
  return result
}
watch(
  () => props.patientInfo.brId,
  (val) => {
    if (val) {
      gmsValue.value = formatValue(props.patientInfo.patientAllergys, props.patientInfo.brGms)
    }
  }
)
</script>
<style lang="less" scoped>
.l {
  text-decoration: underline;
  cursor: pointer;
}
</style>
